package com.example.rbacmanage.controller;

import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.DictType;
import com.example.rbacmanage.exception.MyException;
import com.example.rbacmanage.service.DictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/system/dicttype")
public class DictTypeController {
    @Autowired
    private DictTypeService dictTypeService;

    @GetMapping("/page")
    public Result page(DictType dictType){
        return Result.success(dictTypeService.getPage(dictType));
    }

    @GetMapping("/list")
    public Result list(DictType dictType){
        return Result.success(dictTypeService.getAll(dictType));
    }

    @GetMapping("/{id}")
    public Result info(@PathVariable(value = "id") Long id){
        return Result.success(dictTypeService.getById(id));
    }

    @PreAuthorize("hasAnyAuthority('system:dicttype:add')")
    @PostMapping("/add")
    public Result add(@RequestBody DictType dictType) throws MyException {

        DictType type = new DictType();
        type.setTypeSign(dictType.getTypeSign());
        Integer count = dictTypeService.getCount(type);
        if (count != null && count > 0) {
            throw new MyException("字典类型标识不能重复", HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        dictTypeService.save(dictType);
        return Result.success();
    }

    @PreAuthorize("hasAnyAuthority('system:dicttype:update')")
    @PutMapping("/update")
    public Result update(@RequestBody DictType dictType){
        dictTypeService.update(dictType);
        return Result.success();
    }

    @PreAuthorize("hasAnyAuthority('system:dicttype:remove')")
    @DeleteMapping("/remove")
    public Result remove(@RequestBody Long[] ids){
        dictTypeService.remove(ids);
        return Result.success();
    }
}
